 
package com.glgc.projecti.service.impl;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.glgc.projecti.common.BizException;
import com.glgc.projecti.common.HttpRequestTool;
import com.glgc.projecti.entity.dto.SignDto;
import com.glgc.projecti.service.IHttpService;

@Service
public class HttpServiceImpl implements IHttpService {

	@Value("#{config['access_interface_url_prefix']}")
	public String urlPrefix;
	
	private Logger logger = Logger.getLogger(HttpServiceImpl.class);
	
	@Override
	public boolean sendValiCode(String mobile_tel) throws BizException {
		String urlSuffix = "/api/auth/verifycode?method=new";
		String url = urlPrefix + urlSuffix + "&cellphone=" + mobile_tel + "&kind=0";
		logger.debug("sendValicode url :" + url);
		String resString;
		try {
			resString = HttpRequestTool.httpRequest(url, "POST", null);
			logger.debug("return string: " + resString );
		} catch (BizException e) {
			// TODO Auto-generated catch block
			logger.error("sendValiCode return error_code：" + e.getErrCode() + "; error_info:" + e.getErrInfo());
			throw e;
		}
		return true;
	}
		
	@Override
	public JSONObject signup(SignDto dto) throws BizException {

/*		// 获取当前时间，判断是否已过报名时间	
		Date day=new Date(); //获取当前时间
    	String expDateStr = ResourceBundle.getBundle("config").getString("register_expired_date");
    	
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date expdate = null;
		try {
			expdate = formatter.parse(expDateStr);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		long currentTime = (day.getTime() / 1000) ;   //此时单位为秒，day为上面的Date对象
		long expTime = (expdate.getTime() / 1000) ;     //expdate.getTime()获得的时间以毫秒为单位
		if ( (currentTime - expTime) >= 0) {
			*//**
			 * 返回示例
			    {
				    "errorno": 991010,
				    "errorinfo": "[991010][验证码不存在]\n",
				    "result": {}
				}
			 * *//*
			Map<String, String> map = new HashMap<String, String>();
			map.put("errorno", "999999");
			map.put("errorinfo", "活动进入封闭赛阶段，报名已结束，感谢您的参与！");
			return JSONObject.fromObject(map);
			
		}*/
		
		//进入正常报名流程
		String urlSuffix = "/api/auth/enroll?method=new";
				
		String url = urlPrefix + urlSuffix + "&name=" + dto.getContestantName() +  
				"&cellphone=" + dto.getMobileTel() + 
				"&verify_code=" + dto.getCode()+ 
				"&school=" + dto.getContestantCollege() + 
				"&college=" + dto.getContestantInstitute()+ 
				"&teacher=" + dto.getContestantAdviser() +
				"&iswechat=0";
		logger.debug("signup url :" + url);
		String resString;
		JSONObject resMap = new JSONObject();
		try {
			resString = HttpRequestTool.httpRequest(url, "POST", null);
			logger.debug("return string: " + resString );
			resMap = toJsonObject(resString);
		} catch (BizException e) {
			logger.debug("signup return error_code：" + e.getErrCode() + "; error_info:" + e.getErrInfo());
			throw e;
		} 
		return resMap;
	}
	
	@Override
	public JSONObject getSchoolList() throws BizException {
		//进入正常报名流程
		String urlSuffix = "/api/school?method=list";
				
		String url = urlPrefix + urlSuffix;
		logger.debug("getSchoolList url :" + url);
		String resString;
		JSONObject resMap = new JSONObject();
		try {
			resString = HttpRequestTool.httpRequest(url, "GET", null);
			logger.debug("return string: " + resString );
			resMap = toJsonObject(resString);
		} catch (BizException e) {
			logger.debug("getSchoolList return error_code：" + e.getErrCode() + "; error_info:" + e.getErrInfo());
			throw e;
		}
		return resMap;
	}

	@Override
	public JSONObject getRankList() throws BizException {
		//进入正常报名流程
		String urlSuffix = "//api/match/rank?method=list&mid=1";
				
		String url = urlPrefix + urlSuffix;
		logger.debug("getRankList url :" + url);
		String resString;
		JSONObject resMap = new JSONObject();
		try {
			resString = HttpRequestTool.httpRequest(url, "GET", null);
			logger.debug("return string: " + resString );
			resMap = toJsonObject(resString);
		} catch (BizException e) {
			logger.debug("getRankList return error_code：" + e.getErrCode() + "; error_info:" + e.getErrInfo());
			throw e;
		}
		return resMap;
	}

	private JSONObject toJsonObject(String resString) {
		JSONObject resMap = new JSONObject();
		ObjectMapper om = new ObjectMapper();
		if (resString != null) {
			try {
				resMap = om.readValue(resString.getBytes("UTF-8"), JSONObject.class);
			} catch (Exception e) {
				e.printStackTrace();
			} 
		}
		return resMap;
	}

    public static void main(String [] args) throws Exception {
		SignDto testDTO = new SignDto();
		
		HttpServiceImpl testHttpServiceImpl = new HttpServiceImpl();
		JSONObject result = testHttpServiceImpl.signup(testDTO);
		System.out.println(result);
	}
}
 
